package com.ln.design.mode.proxy.cglib;

import com.ln.design.mode.proxy.AnotherSmsService;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;

/**
 * @Description CglibTest
 * @Author zhangj
 * @Date 2022/12/1 23:21
 */
public class CglibTest {

    public static void main(String[] args) {
        // 创建动态代理增强类
        Enhancer enhancer = new Enhancer();
        // 设置类加载器
        enhancer.setClassLoader(AnotherSmsService.class.getClassLoader());
        // 设置被代理类
        enhancer.setSuperclass(AnotherSmsService.class);
        // 设置方法拦截器
        enhancer.setCallback((MethodInterceptor) (obj, method, args1, proxy) -> {
            //调用方法之前，我们可以添加自己的操作
            System.out.println("before method " + method.getName());
            Object object = proxy.invokeSuper(obj, args1);
            //调用方法之后，我们同样可以添加自己的操作
            System.out.println("after method " + method.getName());
            return object;
        });
        // 创建代理类
        AnotherSmsService proxySmsService  = (AnotherSmsService) enhancer.create();

        proxySmsService.send("java");
    }

}
